package com.tianji.promotion.utils;

import com.tianji.common.exceptions.BizIllegalException;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author : Cammy.Wu
 * Description : 环绕增强的切面，实现加锁、释放锁
 */

@Aspect
@Component
@RequiredArgsConstructor
public class MyLockAspect implements Ordered {

    private final MyLockFactory myLockFactory;

    @Around("@annotation(myLock)")
    public Object tryLock(ProceedingJoinPoint pjp, MyLock myLock) throws Throwable {
        // 1.创建锁对象
//        RLock lock = redissonClient.getLock(myLock.name());
        RLock lock = myLockFactory.getLock(myLock.lockType(), myLock.name());
        // 2.尝试获取锁
//        boolean isLock = lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.unit());
        boolean isLock = myLock.lockStrategy().tryLock(lock, myLock);
        // 3.判断是否成功
        if (!isLock) {
            // 3.1 失败
            return null;// 失败处理策略以及封装到lockStrategy中，此处直接结束，无需处理
        }
        try {
            // 3.2 成功
            return pjp.proceed();
        } finally {
            // 4.释放锁
            lock.unlock();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
